package cn.gov.escience.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.gov.escience.except.UserNotFound;
import cn.gov.escience.model.User;
import cn.gov.escience.repository.UserRepository;
import cn.gov.escience.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserRepository userRepository;

	@Override
	public void addUser(User user) {
		// TODO Auto-generated method stub
		userRepository.save(user);
	}

	@Override
	public void updateUser(User user) throws UserNotFound {
		// TODO Auto-generated method stub
		User userUpdate = userRepository.findOne(user.getId());
		if (userUpdate == null) {
			throw new UserNotFound();
		}
		if (user.getUsername() != null) {
			userUpdate.setUsername(user.getUsername());
		}
		if (user.getPassword() != null) {
			userUpdate.setPassword(user.getPassword());
		}
		userRepository.save(userUpdate);
	}

	@Override
	public void deleteUser(int id) throws UserNotFound {
		// TODO Auto-generated method stub
		User userDelete = userRepository.findOne(id);
		if (userDelete == null) {
			throw new UserNotFound();
		}
		userRepository.delete(id);
	}

	@Override
	public User getUser(int id) {
		// TODO Auto-generated method stub
		return userRepository.findOne(id);
	}

	@Override
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		return userRepository.findAll();
	}

	@Override
	public List<User> getUsersByNameCondition(String name) {
		// TODO Auto-generated method stub
		return userRepository.findByUsernameContaining(name);
	}

	@Override
	public List<User> getUserByPassword(String password) {
		// TODO Auto-generated method stub
		return userRepository.findByPassword(password);
	}

}
